import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login'

// 404
import notFound from '../views/notFount/index.vue'

import layout from '../views/layout/index.vue'
import home from '../views/layout/home/index.vue'
import question from '../views/layout/question/index.vue'
import movie from '../views/layout/movie/index.vue'
import user from '../views/layout/user/index.vue'
import edit from '../views/layout/edit/index.vue'
import article from '../views/layout/article/index.vue'
import search from '../views/layout/search/index.vue'
import result from '../views/layout/result/index.vue'
import student from '../views/layout/student/idnex.vue'

// token工具函数
import { getTkone, removeTkone } from '../utils/token'
// 轻提示
import { Toast } from 'vant'

import { getUserInfo } from '../api/user'
// vuex仓库对象
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/',
    name: 'layout',
    component: layout,
    children: [
      {
        name: 'home',
        path: 'home',
        component: home
      },
      {
        name: 'question',
        path: 'question',
        component: question
      },
      {
        name: 'movie',
        path: 'movie',
        component: movie
      },
      {
        name: 'user',
        path: 'user',
        component: user,
        meta: {
          // 元信息：标记需要登录
          neddLogin: true
        }
      },
      {
        path: 'edit',
        name: 'edit',
        component: edit,
        meta: {
          neddLogin: true,
          // 判断tabber是否要隐藏
          hideTabber: true
        }
      },
      {
        path: 'article',
        name: 'article',
        component: article,
        meta: {
          // 判断tabber是否要隐藏
          hideTabber: true
        }
      },
      {
        path: 'search',
        name: 'search',
        component: search,
        meta: {
          // 判断tabber是否要隐藏
          hideTabber: true
        }
      },
      {
        path: 'result',
        name: 'result',
        component: result,
        meta: {
          // 判断tabber是否要隐藏
          hideTabber: true
        }
      },
      {
        path: 'student',
        name: 'student',
        component: student,
        meta: {
          // 判断tabber是否要隐藏
          hideTabber: true,
          neddLogin: true
        }
      }
    ]
  },
  {
    path: '*',
    name: 'notFound',
    component: notFound
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

// 吞掉 没有处理的 promise的错误
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 执行之后 阻断后续代码
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录才能查看
  // if (to.meta.neddLogin !== true) return next()
  // vuex中有用户信息，不需要做后续判断，直接访问
  if (store.state.userInfo.name !== undefined) return next()
  // 判断是否携带了token，没有去登录，没有token不需要登录
  const tokenObj = getTkone()
  if (tokenObj === null && to.meta.neddLogin !== true) {
    return next()
  }
  // 没有token需要登录
  if (tokenObj === null && to.meta.neddLogin === true) {
    Toast.fail('请先登录！')
    return next({ path: '/login', query: { redirect: to.path } })
  }
  // 表示携带了token，判断token对错（后端判断）
  getUserInfo()
    .then(res => {
      // then里面保存数据到vuex
      store.commit('setUserInfo', res.data.data)
      next()
    })
    .catch(errRos => {
      // comsole.dir(errRos.response.status)
      if (errRos.response.status === 401 || errRos.response.status === 400) {
        // token有问题，直接删除
        removeTkone()
        // 需要登录
        if (to.meta.neddLogin === true) {
          // 提示，重新登录
          Toast.fail('请先登录！')
          return next({ path: '/login', query: { redirect: to.path } })
        }
        // 不需要登录
        return next()
      }
    })
})

export default router
